package com.hopes.bizz.hazard.common.logic;


import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjUtil;
import com.hopes.bizz.common.core.util.DateUtils;
import com.hopes.bizz.hazard.common.constant.CalendarConstant;
import com.hopes.bizz.hazard.common.constant.HazardDicConstant;

import java.util.Date;
import java.util.Optional;


public class AlarmLogic {

    /**
     * 构建持续时间描述信息
     *
     * @param alarmTime       告警时间
     * @param removeTime      消警时间
     * @param durationSecond  持续时长
     * @param alarmStatus     报警状态
     * @return                持续时间
     */
    public static String buildDurationTimeDesc(Date alarmTime, Date removeTime, Long durationSecond, String alarmStatus) {
        if (ObjUtil.isNull(alarmTime) || ObjUtil.isNull(alarmStatus)) {
            return null;
        }
        if (ObjUtil.isNull(removeTime) && HazardDicConstant.HAZ_ALARM_STATUS_REMOVE.equals(alarmStatus)) {
            removeTime = new Date();
        }
        if (ObjUtil.isNotNull(removeTime)) {
            durationSecond = DateUtils.getIntervalSeconds(alarmTime, removeTime);
        }
        return buildDurationTimeDesc(durationSecond);
    }

    /**
     * 构建持续时间描述信息
     *
     * @param durationSecond  持续时间（秒）
     * @return                持续时间描述
     */
    public static String buildDurationTimeDesc(Long durationSecond) {
        final StringBuilder res = new StringBuilder();
        final Optional<Long> durationSecondOptional = Optional.ofNullable(durationSecond);
        if (durationSecondOptional.isEmpty()) {
            res.append("从未上线");
            return res.toString();
        }
        if (durationSecondOptional.get() < CalendarConstant.ONE_MINUTE) {
            res.append("小于一分钟");
        } else {
            final int dayNum = Double.valueOf(NumberUtil.div(durationSecond.intValue(), CalendarConstant.ONE_DAY, 0)).intValue();
            if (dayNum > 0) {
                res.append(dayNum).append("天");
                durationSecond = durationSecond % CalendarConstant.ONE_DAY;
            }
            final int hourNum = Double.valueOf(NumberUtil.div(durationSecond.intValue(), CalendarConstant.ONE_HOUR, 0)).intValue();
            if (hourNum > 0) {
                res.append(hourNum).append("小时");
                durationSecond = durationSecond % CalendarConstant.ONE_HOUR;
            }
            final int minuteNum = Double.valueOf(NumberUtil.div(durationSecond.intValue(), CalendarConstant.ONE_MINUTE, 0)).intValue();
            if (minuteNum > 0) {
                res.append(minuteNum).append("分钟");
            }
        }
        return res.toString();
    }
}
